// pages/danger/selfAdd/index.js
import Dialog from '../../../dist/dialog/dialog.js';
import Toast from '../../../dist/toast/toast.js';

var app = getApp()
var util = require('../../../utils/util.js')
Page({

    /**
     * 页面的初始数据
     */
    data: {
        baseUrl: app.globalData.baseUrl,


        inspectId: 0,
        inspectList: [],
        title: '检查表标题',
        checkNum: '',
        preCheckDate:new Date(),
        preCheckDateStr:'',
        head: ['序号', '检查项目', '检查内容', '操作'],
        hiddenModal: true,
        inspectPublicId: 0,
        processInstanceId: "",
        taskId: "",
        dangerLevelOptions: ['一般(C级)', '一般(B级)', '重大(A级)'],


        selectLevel: "一般（C级）",
        inspectListPublic: {},
        inspectListPublicIndex: 0, //当前编辑的检查项目在inspectList中的index
        deadline: "",
        inspectResult: "", //检查记录
        needChange: false,
        tempImagePaths: [],
        inspectImageIds: [],
        dangerListCount: 0,//统计当前隐患的个数
        companyName: '',
        deptName: '',
        companyId: 0,
        deptId: '',
        inspectType: 0,//检查的类型，0自查，1检查，2排查或督查
        taskDefineKey:'usertask2'//检查表所处的状态  usertask2 -待检查 usertask4-发布整改单 usertask7-待整改 usertask9-待验收
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        var that = this
        this.setData({
            inspectId: options.inspectId,
            taskId: options.taskId,
            inspectType: options.type
        })
        var inspect = options.inspect
        if (inspect == "true") {
            that.loadInspect(options.inspectId)
        } else {
            that.loadInspectPublicDetail(options.inspectId);
        }
    },
    /**
     * 加载隐患自查的模板表
     */
    loadInspect(inspectId) {
        var inspectDate = new Date()
        var header;
        header = {
            'Cookie': wx.getStorageSync("sessionid") //读取cookie
        };

        var that = this
        wx.request({
            header: header,
            method: 'POST',
            url: app.globalData.baseUrl + '/safe/danger/inspectList/find',
            data: {
                inspectId: inspectId,
                sortField: 'inspect_project',
                sortOrder: 'asc'
            },
            success(res) {
                var inspectList = res.data.data
                for (var i = 0; i < inspectList.length; i++) {
                    inspectList[i].inspectResult = "合格"
                    inspectList[i].needChange = 0
                }
                that.setData({
                    inspectList: inspectList
                })
                var checkNum = '';
                if (that.data.inspectType == 0) {
                    checkNum = "隐患自查小程序" + util.formatTime(new Date())
                } else if (that.data.inspectType == 1) {
                    checkNum = "隐患检查小程序" + util.formatTime(new Date())
                } else {
                    checkNum = "隐患排查小程序" + util.formatTime(new Date())
                }
                var params = {
                    dangerInspectListPublicList: inspectList,
                    checkNum: checkNum, //隐患检查编号
                    inspectId: inspectId,
                    leaderUser: "",
                    leaderUserId: "",
                    name: "隐患检查表小程序",
                    predictInspectDate: inspectDate,
                    publicCompanyId: app.globalData.user.companyId,
                    publicDeptId: app.globalData.user.companyId,
                    status: 0,
                    targetDeptId: that.data.companyId,
                    activitiParams: {
                        applyUserId: 1,
                        check: false,
                        type: that.data.inspectType
                    }
                }
                //获取检查表的名字
                wx.request({
                    header: header,
                    url: app.globalData.baseUrl + '/safe/danger/inspect/find',
                    method: 'POST',
                    data: {
                        dangerInspect: {
                            id: inspectId
                        },
                    },
                    success(res) {
                        that.setData({
                            title: res.data.data.list[0].name
                        })
                        params.name = res.data.data.list[0].name + util.formatTime(new Date())
                        that.publicSelfInspect(params, header)
                    }
                })
            }
        })

    },
    /**
     * 显示记录隐患的窗口
     */
    showInspectModal(e) {
        var index = e.currentTarget.dataset.index
        var inspectPublicListId = e.currentTarget.dataset.inpsectpubliclistid
        var inspectPublicList = this.data.inspectList[index]
        this.setData({
            hiddenModal: false,
        })
        this.setData({
            inspectListPublic: inspectPublicList,
            inspectListPublicIndex: index
        })
        this.initInspectListPublic(inspectPublicList)
    },
    /**
     * 点击记录，加载隐患记录的信息
     */
    initInspectListPublic(inspectPublicList) {
        var needChange = false;
        if (inspectPublicList.needChange == 0) {
            needChange = false
        } else {
            needChange = true
        }
        var deadline = ''
        if (inspectPublicList.deadline) {
            deadline = util.formatTime(new Date(inspectPublicList.deadline), 'Y/M/D')

        } else {
            deadline = util.formatTime(new Date())
        }
        let tempPicList=[];
        inspectPublicList.dangerPics.forEach(function (item) {
            tempPicList.push({
                fId:item.fId,
                url:app.globalData.fileUrl+item.path+'?x-oss-process=image/resize,m_fixed,h_70,w_70',
                oriUrl:app.globalData.fileUrl+item.path
            })
        });
        this.setData({
            inspectResult: inspectPublicList.inspectResult,
            deadline: deadline,
            selectLevel: '一般(C级)',
            needChange: needChange,
            tempImagePaths: tempPicList
        })
        if (inspectPublicList.hiddenDangerLevel) {
            this.setData({
                selectLevel: inspectPublicList.hiddenDangerLevel,
            })
        }
    },
    /**
     * 将隐患检查记录的结果暂存到data中去
     */
    bindInspectResultBlur(e) {
        this.setData({
            inspectResult: e.detail.value
        })
    },
    /**
     * 隐藏窗口
     */
    hiddenInspectModal() {
        this.setData({
            hiddenModal: true
        })
    },
    /**
     * 保存单个隐患检查记录
     */
    saveInspectList() {
        var that = this
        var inspectNeedChange = 0;
        if (this.data.needChange) {
            inspectNeedChange = 1;
        }
        var header = {
            'Cookie': wx.getStorageSync("sessionid") //读取cookie
        };
        var params = {
            inspectResult: this.data.inspectResult,
            deadline: this.data.deadline,
            id: this.data.inspectListPublic.id,
            needChange: inspectNeedChange,
            hiddenDangerLevel: this.data.selectLevel
        }
        wx.showLoading({
            title: '保存中.....',
        })
        wx.request({
            url: app.globalData.baseUrl + '/safe/danger/inspectListPublic/update',
            header: header,
            method: "POST",
            data: params,
            success(res) {
                if (res.data.success) {
                    var param = "inspectList[" + that.data.inspectListPublicIndex + "]"
                    var inspectListPublic = that.data.inspectList[that.data.inspectListPublicIndex]
                    inspectListPublic.deadline = that.data.deadline
                    inspectListPublic.needChange = that.data.needChange
                    inspectListPublic.hiddenDangerLevel = that.data.selectLevel
                    inspectListPublic.inspectResult = that.data.inspectResult
                    inspectListPublic.deadlineStr = util.formatTime(new Date(that.data.deadline))
                    var inspectList = that.data.inspectList
                    inspectList[that.data.inspectListPublicIndex] = inspectListPublic
                    that.countDanger()
                    wx.hideLoading()
                    that.setData({
                        inspectList: inspectList,
                        hiddenModal: true
                    })
                }
            }
        })
    },

    /**
     * 统计当前隐患个个数
     */
    countDanger() {
        var inspectList = this.data.inspectList
        var count = 0;
        for (var i = 0; i < inspectList.length; i++) {
            if (inspectList[i].needChange == 1) {
                count = count + 1;
            }
        }
        this.setData({
            dangerListCount: count
        })
    },
    /**
     * 选择隐患照片
     */
    chooseInspectImage() {
        var that = this
        if (this.data.tempImagePaths.length >= 3) {
            wx.showToast({
                title: '隐患图片最多添加3张',
                icon: 'none',
            })
            return
        }
        wx.chooseImage({
            count: 1,
            success: function (res) {
                if (res.tempFilePaths.length > 0) {
                    let tempFile=res.tempFilePaths[0];
                    wx.request({
                        url: app.globalData.baseUrl + '/safe/sys/oss/sign',
                        method: 'get',
                        data: { contentId: that.data.inspectListPublic.id, contentType:4},//隐患排查的照片
                        success(res) {
                            wx.uploadFile({
                                url: app.globalData.fileUrl,
                                filePath: tempFile,
                                name: 'file',
                                formData: {
                                    name:tempFile,
                                    key:res.data.dir + tempFile,
                                    policy:res.data.policy,
                                    OSSAccessKeyId:res.data.accessid,
                                    success_action_status:'200',
                                    signature:res.data.signature,
                                    callback:res.data.callback
                                },
                                success: function (res) {
                                    let resultJson=JSON.parse(res.data);
                                    let decodeDataJson=util.decode(resultJson.file);
                                   let newPicList=that.data.tempImagePaths;
                                   //修改显示图片列表
                                   newPicList.push({
                                       fId:decodeDataJson.fId,
                                       url:app.globalData.fileUrl+decodeDataJson.path+'?x-oss-process=image/resize,m_fixed,h_70,w_70',
                                       oriUrl:app.globalData.fileUrl+decodeDataJson.path
                                   });
                                   //修改全体数据
                                    var dangerInspectLstPublic = that.data.inspectList[that.data.inspectListPublicIndex]
                                    dangerInspectLstPublic.dangerPics.push({fId:decodeDataJson.fId, path:decodeDataJson.path})
                                    var inspectList = that.data.inspectList
                                    inspectList[that.data.inspectListPublicIndex] = dangerInspectLstPublic
                                    that.setData({
                                        tempImagePaths:newPicList,
                                        inspectList: inspectList
                                    })
                                }
                            })

                        }
                    })

                }
            },
        })
    },

    /**
     * 删除上传的隐患照片
     */
    deleteInspectImage(e) {
        var imageIndex = e.currentTarget.dataset.index
        var that = this
        Dialog.confirm({
            title: '删除照片',
            message: '确认删除隐患照片'
        }).then(() => {
            var header = {
                'Cookie': wx.getStorageSync("sessionid") //读取cookie
            };
            var fId = that.data.tempImagePaths[imageIndex].fId
            wx.request({
                url: app.globalData.baseUrl + '/safe/file/delete?fId=' + fId,
                header: header,
                method: "GET",
                success(res) {
                    if (res.data.success) {
                        // Toast('删除照片成功');
                        var tempImagePaths = that.data.tempImagePaths
                        tempImagePaths.splice(imageIndex, 1)
                        that.setData({
                            tempImagePaths: tempImagePaths
                        })
                        //更新隐患检查单中的隐患照片信息
                        var dangerInspectLstPublic = that.data.inspectList[that.data.inspectListPublicIndex]
                        dangerInspectLstPublic.dangerPics.splice(imageIndex, 1)
                        var inspectList = that.data.inspectList
                        inspectList[that.data.inspectListPublicIndex] = dangerInspectLstPublic
                        that.setData({
                            inspectList: inspectList
                        })
                    } else {
                        // Toast('删除照片失败，可能网络错误或者网页端已删除');
                    }
                }
            })

        }).catch(() => {

        })
    },
    /**
     * 隐患级别选择
     */
    dangerLevelSelect(e) {
        console.log('picker发送选择改变，携带值为', e.detail.value)
        this.setData({
            selectLevel: this.data.dangerLevelOptions[e.detail.value]
        })
        var param = "inspectPublicList.hiddenDangerLevel"
        this.setData({
            [param]: this.data.dangerLevelOptions[e.detail.value]
        })
    },
    /**
     * 记录隐患整改期限
     */
    inspectListChangeData(e) {
        var param = "inspectListPublic.deadline"
        console.log('picker发送选择改变，携带值为', e.detail.value)
        this.setData({
            [param]: e.detail.value
        })
        this.setData({
            deadline: e.detail.value
        })
    },
    /**
     * 隐患检查记录是否需要整改
     */
    needChangeSwitch(e) {
        this.setData({
            needChange: e.detail.value
        })

    },
    /**
     * 将加载的自查表发布
     */
    publicSelfInspect(params, header) {

        var that = this
        params.status = 2
        wx.request({
            header: header,
            url: app.globalData.baseUrl + '/safe/dangerFlow/startDangerFlow',
            method: 'POST',
            data: params,
            success(res) {

                if (res.data.success) {
                    var inspectPublicId = res.data.data.businesskey
                    that.setData({
                        inspectPublicId: inspectPublicId
                    })
                    that.loadInspectPublicDetail(inspectPublicId)
                    if (res.data.data.myTasks.length > 0) {
                        that.setData({
                            taskId: res.data.data.myTasks[0].id
                        })
                    }
                }
            }
        })
    },
    /**
     * 保存检查时间
     */
    saveInspectDate() {
        var header;
        header = {
            'Cookie': wx.getStorageSync("sessionid") //读取cookie
        };
        var that = this
        var params = {
            inspectDate: new Date(),
            id: that.data.inspectPublicId
        }
        wx.request({
            header: header,
            url: app.globalData.baseUrl + '/safe/danger/inspectPublic/update',
            method: 'POST',
            data: params,
            success(res) {
                //保存返回到待检查列表去
                wx.redirectTo({
                    url:'/pages/danger/dangerTaskList/dangerTaskList?taskDefineKey=usertask2&taskListTitle=待检查'
                })

            }
        })
    },
    /**
     * 加载发布的隐患排查的检查单
     */
    loadInspectPublicDetail(inspectPublicId) {

        var that = this
        var header;
        that.setData({
            inspectPublicId: inspectPublicId
        })
        header = {
            'Cookie': wx.getStorageSync("sessionid") //读取cookie
        };
        wx.request({
            url: app.globalData.baseUrl + '/safe/danger/inspectPublic/detail',
            header: header,
            method: "POST",
            data: {
                id: inspectPublicId
            },
            success(res) {
                var inspectList = res.data.data.dangerInspectListPublicList
                that.setData({
                    inspectType: res.data.data.type,
                    checkNum:res.data.data.checkNum,
                })
                for (var i = 0; i < inspectList.length; i++) {
                    if (inspectList[i].deadline) {
                        inspectList[i].deadlineStr = util.formatTime(new Date(inspectList[i].deadline))
                    } else {
                        inspectList[i].deadlineStr = "无"
                    }
                    if (!inspectList[i].hiddenDangerLevel) {
                        inspectList[i].hiddenDangerLevel = "无"
                    }
                }
                if(res.data.data.predictInspectDate){
                    var preCheckDate=new Date(res.data.data.predictInspectDate)
                    that.setData({
                        preCheckDateStr:util.formatTime(preCheckDate),
                        preCheckDate:res.data.data.predictInspectDate
                    })
                }
                that.setData({
                    inspectList: res.data.data.dangerInspectListPublicList,
                    title: res.data.data.name
                })
                that.countDanger()
            }
        })
    },
    /**
     * 预览隐患照片
     */
    previewDangerImage(e) {
        var src = e.currentTarget.dataset.src;
        var imageList = new Array();
        for (var i = 0; i < this.data.tempImagePaths.length; i++) {
            imageList.push(this.data.tempImagePaths[i].oriUrl)
        }
        wx.previewImage({
            current: src,
            urls: imageList,
        })
    },

    //提交当前任务
    doTask(e) {
        var that = this
        Dialog.confirm({
            title: '提示',
            message: '是否提交检查结果',
            selector: '#van-dialog-doTask',

        }).then(() => {
            var header;

            header = {
                'Cookie': wx.getStorageSync("sessionid"),//读取cookie
                'content-type': 'application/x-www-form-urlencoded'
            };
            var params = {taskId: that.data.taskId,}

            if (that.data.inspectType == 0) {
                params.type = 0
                params.reform = false
                if (that.data.dangerListCount > 0) {
                    params.danger = true
                    params.applyUserId = app.globalData.user.userId
                    var userIds = new Array()
                    userIds.push(app.globalData.user.userId)
                    params.userIds = userIds
                } else {
                    params.danger = false
                }
            }
            if (that.data.inspectType == 1) {
                params.type = 1
                if (that.data.dangerListCount > 0) {
                    params.danger = true
                    params.reform = true

                } else {
                    params.danger = false
                    params.reform = false
                }
            }
            if (that.data.inspectType == 2) {
                params.type = 2
                if (that.data.dangerListCount > 0) {
                    params.danger = true
                    params.reform = true

                } else {
                    params.danger = false
                    params.reform = false
                }
            }


            wx.request({
                url: app.globalData.baseUrl + '/safe/dangerFlow/doTask',
                header: header,
                method: "POST",
                data: params,
                success(res) {
                    wx.navigateBack({
                        delta: 1
                    })
                }
            })
        }).catch(() => {
        });
    },
    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function () {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {

    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function () {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function () {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function () {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function () {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function () {

    }
})